package com.flyco.modules.pms.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.constant.CommonConstant;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.BizUtil;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.commonUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.*;
import com.flyco.modules.pms.model.*;
import com.flyco.modules.pms.service.*;
import com.flyco.modules.pms.vo.PmsProductExportVO;
import com.flyco.modules.pms.vo.PmsProductPicsVO;
import com.flyco.modules.pms.wxmavo.WxMaShopSkuAttribute;
import com.flyco.modules.pms.wxmavo.WxMaShopSkuInfo;
import com.flyco.modules.pms.wxmavo.WxMaShopSpuInfo;
import com.flyco.modules.stm.entity.StmStock;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmChannelPriceService;
import com.flyco.modules.stm.service.IStmStockService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.system.entity.SysOpenAccount;
import com.flyco.modules.system.service.ISysOpenAccountService;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 商品信息
 * @Author: flyco
 * @Date: 2019-11-19
 * @Version: V1.0
 * 只有新增和列表查询是不一样的，其他和V1接口一样
 */
@Slf4j
@Api(tags = "商品信息")
@RestController
@RequestMapping("/f/pms/pmsProductV2")
public class PmsProductV2Controller extends BaseController<PmsProduct, IPmsProductService> {
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IPmsSkuStockService pmsSkuStockService;
    @Autowired
    private IPmsProductAttributeService pmsProductAttributeService;
    @Autowired
    private IPmsProductAttributeValueService pmsProductAttributeValueService;
    @Autowired
    private IPmsBrandService pmsBrandService;
    @Autowired
    private IPmsProductCategoryService pmsProductCategoryService;
    @Autowired
    private IPmsProductPicsService pmsProductPicsService;
    @Autowired
    private IPmsProductQualificationPicsService pmsProductQualificationPicsService;
    @Autowired
    private IPmsProductPriceRegulateService pmsProductPriceRegulateService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IStmStockService stmStockService;
    @Autowired
    private ISysOpenAccountService sysOpenAccountService;
    @Autowired
    private IStmJdWmsStockService wmsStockService;

    /**
     * 查询所有经销商，遍历每个经销商的网点，如果经销商的商品网点没有库存记录，就初始化一条记录
     */
    @AutoLog(value = "库存记录同步到网点")
    @ApiOperation(value = "库存记录同步到网点", notes = "库存记录同步到网点")
    @PostMapping(value = "/toNetStock")
    public Result<?> toNetStock() {
        return pmsProductService.toNetStock(2);
    }

    /**
     * 分页列表查询
     *
     * @param pmsProduct
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商品信息-分页列表查询")
    @ApiOperation(value = "商品信息-分页列表查询", notes = "商品信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(PmsProduct pmsProduct,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Map<String, String[]> paramMap = commonUtil.moveMapItem(req.getParameterMap(), "column");
        QueryWrapper<PmsProduct> queryWrapper = QueryGenerator.initQueryWrapper(pmsProduct, paramMap);
        queryWrapper.orderByAsc("id");
        List<PmsProductCategory> pmsProductCategories = pmsProductCategoryService.list();

        if (pmsProduct.getProductCategoryIdLevel1() != null) {
            if (pmsProductCategories.size() > 0) {
                queryWrapper.in("product_category_id", pmsProductCategories.stream().
                        filter(a -> a.getId() == pmsProduct.getProductCategoryIdLevel1() || a.getParentId() == pmsProduct.getProductCategoryIdLevel1())
                        .map(PmsProductCategory::getId).collect(Collectors.toList()));
            }
        }
        Page<PmsProduct> page = new Page<PmsProduct>(pageNo, pageSize);
        Map<Long, PmsProductCategory> pmsProductCategoryMap = new HashMap<>();
        pmsProductCategories.forEach(a -> pmsProductCategoryMap.put(a.getId(), a));
        IPage<PmsProduct> pageList = pmsProductService.page(page, queryWrapper);
        pageList.getRecords().forEach(a -> {

            a.setBrandName(pmsBrandService.getById(a.getBrandId()).getName());
            if (a.getProductCategoryId() != null) {
                if (pmsProductCategoryMap.get(a.getProductCategoryId()).getLevel() == 1) {
                    //a.setProductCategoryNameLevel1(a.getProductCategoryName());
                    a.setProductCategoryNameLevel1(pmsProductCategoryMap.get(a.getProductCategoryId()).getName());
                } else {
                    Long parentId = pmsProductCategoryMap.get(a.getProductCategoryId()).getParentId();
                    a.setProductCategoryNameLevel1(pmsProductCategoryMap.get(parentId).getName());
                    a.setProductCategoryNameLevel2(a.getProductCategoryName());
                }
            }
        });
        return Result.ok(pageList);
    }


    /**
     * 分页商品库列表查询
     *
     * @param pmsProduct
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商品信息-分页商品库列表查询")
    @ApiOperation(value = "商品信息-分页商品库列表查询", notes = "商品信息-分页商品库列表查询")
    @GetMapping(value = "/productList")
    public Result<?> queryProductPageList(PmsProduct pmsProduct,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                          HttpServletRequest req) {
        QueryWrapper<PmsProduct> queryWrapper = QueryGenerator.initQueryWrapper(pmsProduct, req.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<PmsProduct> page = new Page<PmsProduct>(pageNo, pageSize);
        IPage<PmsProduct> pageList = pmsProductService.getProductPage(page, queryWrapper, sysUser.getPartnerId());
        pageList.getRecords().forEach(item->{
            item.setStock(wmsStockService.getOne(new LambdaQueryWrapper<StmJdWmsStock>().eq(StmJdWmsStock::getSkuCode,item.getSkuCode())).getStock());
        });
        return Result.ok(pageList);
    }

    /**
     * 批量添加
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品信息-批量添加")
    @ApiOperation(value = "商品信息-批量添加", notes = "商品信息-批量添加")
    @PostMapping(value = "/addBatch")
    public Result<?> addBatch(@RequestBody String[] ids) {
        log.info("ids:" + ids);
        List<Long> idList = Arrays.stream(ids)
                .map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<PmsProduct> products = pmsProductService.getProductListWithOutPartner(idList);
        List<String> productSnList = products.stream().map(PmsProduct::getProductSn).collect(Collectors.toList());
        LambdaQueryWrapper<PmsProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PmsProduct::getProductSn, productSnList);
        List<PmsProduct> dbProduct = pmsProductService.list(queryWrapper);
        List<String> dbProductSnList = dbProduct.stream().map(PmsProduct::getProductSn).collect(Collectors.toList());
        List<PmsProduct> removeProducts = products.stream().filter(r -> dbProductSnList.contains(r.getProductSn())).collect(Collectors.toList());
        products.removeAll(removeProducts);
        if (products.size() > 0) {
            List<Long> addIds = products.stream().map(PmsProduct::getId).collect(Collectors.toList());
            List<PmsProductPics> pics = pmsProductPicsService.selectByMainIds(addIds);
            Map<Long, List<PmsProductPics>> voMap = pics.stream().collect(Collectors.groupingBy(e -> e.getProductId()));
            List<PmsProductPicsVO> picsVOS = new ArrayList<>();
            products.forEach(p -> {
                PmsProductPicsVO vo = new PmsProductPicsVO();
                vo.setProduct(p);
                vo.setProductPics(voMap.get(p.getId()));
                picsVOS.add(vo);
            });
            pmsProductService.saveMainWithPics(picsVOS);
        }
        String errMsg = "";
        if (dbProductSnList.size() > 0) {
            errMsg = "已存在货号：" + dbProductSnList.toString();
        }

        return Result.ok("添加成功！" + errMsg);
    }


    /**
     * 添加
     *
     * @param pmsProductModel
     * @return
     */
    @AutoLog(value = "商品信息-添加")
    @ApiOperation(value = "商品信息-添加", notes = "商品信息-添加")
    @PostMapping(value = "/add")
    //@Transactional
    public Result<?> add(@RequestBody PmsProductModel pmsProductModel) {
        PmsProduct pmsProduct = BeanUtils.instantiateClass(PmsProduct.class);
        BeanUtils.copyProperties(pmsProductModel, pmsProduct);
        PmsBrand brand = pmsBrandService.getById(pmsProduct.getBrandId());
        if (oConvertUtils.isNotEmpty(brand)) {
            pmsProduct.setBrandName(brand.getName());
        }
        PmsProductCategory category = pmsProductCategoryService.getById(pmsProduct.getProductCategoryId());
        LambdaQueryWrapper<PmsProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PmsProduct::getDeleteStatus, 0);
        queryWrapper.in(PmsProduct::getSkuCode, pmsProduct.getSkuCode());
        List<PmsProduct> products = pmsProductService.list(queryWrapper);
        if (products.size() > 0) {
            return Result.error("skuCode重复！");
        }
        pmsProduct.setProductCategoryName(category.getName());
        pmsProduct.setPublishStatus("0");
        pmsProduct.setWxStatus(0);
        pmsProduct.setCreateBy("");
        pmsProduct.setCreateTime(null);
        pmsProduct.setUpdateBy("");
        pmsProduct.setUpdateTime(null);
        pmsProduct.setBrandCategory(2);
        //setSkuName(pmsProduct);
        pmsProduct.setProductSn(pmsProduct.getSkuCode());
        pmsProductService.save(pmsProduct);
        PmsSkuStock pmsSkuStock = new PmsSkuStock();
        pmsSkuStock.setSkuCode(pmsProduct.getSkuCode());
        pmsSkuStock.setStoreId(0l);
        pmsSkuStock.setProductId(pmsProduct.getId());
        pmsSkuStock.setProductSn(pmsProduct.getProductSn());
        pmsSkuStock.setCreateTime(new Date());
        pmsSkuStockService.save(pmsSkuStock);
        //添加库存
        StmJdWmsStock wmsStock = new StmJdWmsStock();
        wmsStock.setPartnerId(4100L);
        wmsStock.setSkuCode(pmsProduct.getSkuCode());
        wmsStock.setProductName(pmsProduct.getName());
        wmsStock.setStock(pmsProduct.getStock());
        wmsStock.setCreateTime(new Date());
        wmsStockService.save(wmsStock);
        List<PmsProductAttributeModel> attrList = pmsProductModel.getAttrList();
        List<PmsProductAttributeModel> paramList = pmsProductModel.getParamList();
        pmsProductAttributeValueService.saveFromProduct(pmsProduct.getId(), attrList);
        pmsProductAttributeValueService.saveFromProduct(pmsProduct.getId(), paramList);
        return Result.ok("添加成功！");
    }

    private void setSkuName(PmsProduct pmsProduct) {
        //如果页面编辑了，就用页面的值，否则就按照规则组装
        if (StrUtil.isNotBlank(pmsProduct.getSkuName())) {
            return;
        }
        String skuName = pmsProduct.getName();
        try {
            List<String> tags = getContent(pmsProduct.getName());
            skuName = tags.get(1) + pmsProduct.getProductSn() + (StrUtil.isBlank(pmsProduct.getColor()) ? "" : pmsProduct.getColor()) + tags.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pmsProduct.setSkuName(skuName);
    }

    /**
     * 解析标签内容
     * 总是返回2个值
     */
    private static List<String> getContent(String str) {
        List<String> list = new ArrayList<>(2);
        for (int i = 0; i < 2; i++) {
            if (str.contains("【") && str.contains("】")) {
                String tag1 = str.substring(str.indexOf("【"), str.indexOf("】") + 1);
                list.add(tag1);
                str = str.substring(str.indexOf("】") + 1);
            }
        }

        int size = list.size();
        for (int i = 0; i < 2 - size; i++) {
            list.add("");
        }

        return list;
    }

    /**
     * 编辑
     *
     * @param pmsProductModel
     * @return
     */
    @AutoLog(value = "商品信息-编辑")
    @ApiOperation(value = "商品信息-编辑", notes = "商品信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody PmsProductModel pmsProductModel) {
        PmsProduct pmsProduct = BeanUtils.instantiateClass(PmsProduct.class);
        BeanUtils.copyProperties(pmsProductModel, pmsProduct);
        pmsProduct.setProductSn(pmsProduct.getSkuCode());
        PmsBrand brand = pmsBrandService.getById(pmsProduct.getBrandId());
        if (oConvertUtils.isNotEmpty(brand)) {
            pmsProduct.setBrandName(brand.getName());
        }
        PmsProductCategory category = pmsProductCategoryService.getById(pmsProduct.getProductCategoryId());
        if (oConvertUtils.isNotEmpty(category)) {
            pmsProduct.setProductCategoryName(category.getName());
        }
        pmsProductService.updateById(pmsProduct);
        //编辑时如果库存不存在，则直接新增
        StmJdWmsStock wmsStock = wmsStockService.getOne(new QueryWrapper<StmJdWmsStock>().eq("sku_code", pmsProduct.getSkuCode()));
        if (wmsStock == null) {
            wmsStock = new StmJdWmsStock();
            wmsStock.setPartnerId(4100L);
            wmsStock.setSkuCode(pmsProduct.getSkuCode());
            wmsStock.setProductName(pmsProduct.getName());
            wmsStock.setStock(pmsProduct.getStock());
            wmsStock.setCreateTime(new Date());
            wmsStockService.save(wmsStock);
        }else{
            //更新库存
            wmsStock.setStock(pmsProduct.getStock());
            wmsStockService.update(new UpdateWrapper<StmJdWmsStock>().set("stock", pmsProduct.getStock()).eq("sku_code", pmsProduct.getSkuCode()));
        }


        /*StmProduct stmProduct = BeanUtils.instantiateClass(StmProduct.class);
        BeanUtils.copyProperties(pmsProduct, stmProduct);
        stmProductService.updateById(stmProduct);*/
        List<PmsProductAttributeModel> attrList = pmsProductModel.getAttrList();
        List<PmsProductAttributeModel> paramList = pmsProductModel.getParamList();
        pmsProductAttributeValueService.saveFromProduct(pmsProduct.getId(), attrList);
        pmsProductAttributeValueService.saveFromProduct(pmsProduct.getId(), paramList);
        return Result.ok("编辑成功!");
    }

    /**
     * 编辑图片
     *
     * @param pmsProduct
     * @return
     */
    @AutoLog(value = "商品信息-编辑图片")
    @ApiOperation(value = "商品信息-编辑图片", notes = "商品信息-编辑图片")
    @PutMapping(value = "/editProduct")
    public Result<?> editProduct(@RequestBody PmsProduct pmsProduct) {
        pmsProductService.updateById(pmsProduct);
        if (StringUtils.isNotBlank(pmsProduct.getPicWap())) {
            String[] picWaps = pmsProduct.getPicWap().split(",");
            LambdaQueryWrapper<PmsProductPics> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(PmsProductPics::getProductId, pmsProduct.getId());
            pmsProductPicsService.remove(queryWrapper);
            List<PmsProductPics> pmsProductPicss = new ArrayList<>();
            for (String picWap : picWaps) {
                PmsProductPics pmsProductPics = new PmsProductPics();
                pmsProductPics.setPicUrl(picWap);
                pmsProductPics.setProductId(pmsProduct.getId());
                pmsProductPicss.add(pmsProductPics);
            }
            if (pmsProductPicss.size() > 0) {
                pmsProductPicsService.saveBatch(pmsProductPicss);
            }
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 编辑图片
     *
     * @param pmsProduct
     * @return
     */
    @AutoLog(value = "商品信息-编辑状态")
    @ApiOperation(value = "商品信息-编辑状态", notes = "商品信息-编辑状态")
    @PutMapping(value = "/editProductStatus")
    public Result<?> editProductStatus(@RequestBody PmsProduct pmsProduct) {

        PmsProduct product = pmsProductService.getById(pmsProduct.getId());
        //判断必填项，如果没有填写，不让上架售卖
       if(product.getProductCategoryId()==null) {
           return Result.error("商品类别未设置，请设置后再设置线上销售!");
       }
        LambdaQueryWrapper<PmsSkuStock> query = new LambdaQueryWrapper<>();
        query.eq(PmsSkuStock::getProductId, pmsProduct.getId());
        pmsProductService.updateById(pmsProduct);

        return Result.ok("编辑成功!");

    }

    /**
     * 微信交易组件-SPU上/下架
     *
     * @param productId
     * @return
     */
    private String syncListingSpu(Long productId, String status) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysOpenAccount openAccount = sysOpenAccountService.getAccountByPartnerAndBizCode(sysUser.getPartnerId(), CommonConstant.OPEN_ACCOUNT_BIZ_CODE_MINIAPP, CommonConstant.OPEN_ACCOUNT_SOURCE_WECHAT);
        if (oConvertUtils.isEmpty(openAccount)) return "开发平台账户配置表未配账号，请联系管理员！";
        StringBuilder url = new StringBuilder();
        url.append(BizUtil.getWxmaUrl());
        url.append("/wx/miniapp/shop/spu/");
        url.append(openAccount.getClientKey());
        //url.append("wx5003af1ba4f23e32");
        if (Objects.equals("1", status))
            url.append("/listingSpu");
        else
            url.append("/delistingSpu");

        log.info("url: {}", url);
        JSONObject params = new JSONObject();
        params.put("id", productId);

        String result = HttpUtil.postRequest(url.toString(), params);
        log.info("result: {}", result);
        return null;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品信息-通过id删除")
    @ApiOperation(value = "商品信息-通过id删除", notes = "商品信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        LambdaQueryWrapper<PmsSkuStock> stockQueryWrapper = new LambdaQueryWrapper<>();
        stockQueryWrapper.eq(PmsSkuStock::getProductId, id);
        List<PmsSkuStock> stocks = pmsSkuStockService.list(stockQueryWrapper);
        List<PmsSkuStock> inStocks = stocks.stream().filter(r -> (r.getStock() - r.getLockStock()) > 0).collect(Collectors.toList());
        if (oConvertUtils.isNotEmpty(inStocks) && inStocks.size() > 0) {
            return Result.error("经销商中还有库存或赠品，请处理!");
        }

        pmsProductService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品信息-批量删除")
    @ApiOperation(value = "商品信息-批量删除", notes = "商品信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.pmsProductService.removeByIds(Arrays.asList(ids.split(",")));
        //this.stmProductService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品信息-通过id查询")
    @ApiOperation(value = "商品信息-通过id查询", notes = "商品信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        PmsProduct pmsProduct = pmsProductService.getById(id);
        return Result.ok(pmsProduct);
    }


    /**
     * 查询所有商品
     *
     * @return
     */
    @AutoLog(value = "商品信息-查询所有商品")
    @ApiOperation(value = "商品信息-查询所有商品", notes = "商品信息-查询所有商品")
    @GetMapping(value = "/queryList")
    public Result<?> queryList() {
        LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<>();
        query.select(PmsProduct::getId, PmsProduct::getName, PmsProduct::getProductSn);
        List<PmsProduct> products = pmsProductService.list(query);
        return Result.ok(products);
    }

    /**
     * 通过商品ID和属性类型查该类型下的所有属性
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品信息-查该商品的属性")
    @ApiOperation(value = "商品信息-查该商品的属性", notes = "商品信息-查该商品的属性")
    @GetMapping(value = "/queryAttrById")
    public Result<?> queryAttrById(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "productId", defaultValue = "0") String productId) {
        List<PmsProductAttributeModel> list = new ArrayList<>();
        if ("0".equals(productId)) {
            LambdaQueryWrapper<PmsProductAttribute> query = new LambdaQueryWrapper<>();
            query.eq(PmsProductAttribute::getProductAttributeCategoryId, Long.valueOf(id));
            List<PmsProductAttribute> attributeList = pmsProductAttributeService.list(query);
            if (!CollectionUtils.isEmpty(attributeList)) {
                for (PmsProductAttribute attribute : attributeList) {
                    PmsProductAttributeModel model = BeanUtils.instantiateClass(PmsProductAttributeModel.class);
                    BeanUtils.copyProperties(attribute, model);
                    list.add(model);
                }
            }
        } else {
            list = pmsProductAttributeValueService.selectAttributeByCategoryId(Long.valueOf(productId), Long.valueOf(id));
        }
        return Result.ok(list);
    }


    /**
     * 获取被逻辑删除的商品列表，无分页
     *
     * @return logicDeletedProductList
     */
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        List<PmsProduct> logicDeletedProductList = pmsProductService.queryLogicDeleted();
        return Result.ok(logicDeletedProductList);
    }

    /**
     * 还原被逻辑删除的商品
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
    public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String productIds = jsonObject.getString("productIds");
        if (StringUtils.isNotBlank(productIds)) {
            PmsProduct updateProduct = new PmsProduct();
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            updateProduct.setUpdateBy(sysUser.getUsername());
            updateProduct.setUpdateTime(new Date());
            pmsProductService.revertLogicDeleted(Arrays.asList(productIds.split(",")), updateProduct);
            //stmProductService.revertLogicDeleted(Arrays.asList(productIds.split(",")), updateProduct);
        }
        return Result.ok("还原成功");
    }


    //===========================交易组件操作功能========================================

    /**
     * 微信小程序交易组件同步
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品信息-微信小程序交易组件同步")
    @ApiOperation(value = "商品信息-微信小程序交易组件同步", notes = "商品信息-微信小程序交易组件同步")
    @PostMapping(value = "/wxmaSyncBatch")
    public Result<?> wxmaSyncBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        if (oConvertUtils.isEmpty(list)) return Result.error("同步错误，传入参数有问题！");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysOpenAccount openAccount = sysOpenAccountService.getAccountByPartnerAndBizCode(sysUser.getPartnerId(), CommonConstant.OPEN_ACCOUNT_BIZ_CODE_MINIAPP, CommonConstant.OPEN_ACCOUNT_SOURCE_WECHAT);
        if (oConvertUtils.isEmpty(openAccount)) return Result.error("开发平台账户配置表未配账号，请联系管理员！");
        StringBuilder errMsg = new StringBuilder("");
        LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<>();
        query.in(PmsProduct::getId, list);
        List<PmsProduct> products = pmsProductService.list(query);
        List<Long> categoryIds = products.stream().map(PmsProduct::getProductCategoryId).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<PmsProductCategory> categoryQueryWrapper = new LambdaQueryWrapper<>();
        categoryQueryWrapper.in(PmsProductCategory::getId, categoryIds);
        List<PmsProductCategory> categoryList = pmsProductCategoryService.list(categoryQueryWrapper);
        Map<Long, PmsProductCategory> categoryMap = categoryList.stream().collect(Collectors.toMap(PmsProductCategory::getId, Function.identity(), (key1, key2) -> key2));
        LambdaQueryWrapper<PmsSkuStock> skuQuery = new LambdaQueryWrapper<>();
        skuQuery.in(PmsSkuStock::getProductId, list);
        skuQuery.eq(PmsSkuStock::getStoreId, 0);
        List<PmsSkuStock> skuStocks = pmsSkuStockService.list(skuQuery);
        Map<Long, PmsSkuStock> skuMaps = skuStocks.stream().collect(Collectors.toMap(PmsSkuStock::getProductId, Function.identity(), (key1, key2) -> key2));

        LambdaQueryWrapper<PmsProductPics> picQuery = new LambdaQueryWrapper<>();
        picQuery.in(PmsProductPics::getProductId, list);
        picQuery.eq(PmsProductPics::getDelFlag, 0);
        picQuery.orderByAsc(PmsProductPics::getSort);
        List<PmsProductPics> pics = pmsProductPicsService.list(picQuery);
        Map<Long, List<PmsProductPics>> picMap = pics.stream().collect(Collectors.groupingBy(e -> e.getProductId()));

        List<WxMaShopSpuInfo> spuInfos = new ArrayList<>();
        products.forEach(product -> {
            boolean isNewFlag = true;
            if (oConvertUtils.isNotEmpty(product.getWxStatus()) && Objects.equals(1, product.getWxStatus())) {
                isNewFlag = false;
            }
            if (!skuMaps.containsKey(product.getId())) {
                errMsg.append("货号" + product.getProductSn() + "对应的SKU没有维护");
                return;
            }
            if (!categoryMap.containsKey(product.getProductCategoryId())) {
                errMsg.append("货号" + product.getProductSn() + "对应的分类没有维护");
                return;
            }
            PmsProductCategory category = categoryMap.get(product.getProductCategoryId());
            if (oConvertUtils.isEmpty(category.getWxCatId())) {
                errMsg.append("分类" + category.getName() + "对应的微信类目没有维护");
                return;
            }
            boolean isQualification = false;
            List<String> qualificationPicList = new ArrayList<>();
            if (oConvertUtils.isNotEmpty(category.getWxQualificationFlag()) && Objects.equals(1, category.getWxQualificationFlag())) {
                LambdaQueryWrapper<PmsProductQualificationPics> qualificationPicsQuery = new LambdaQueryWrapper<>();
                qualificationPicsQuery.eq(PmsProductQualificationPics::getProductId, product.getId());
                qualificationPicsQuery.eq(PmsProductQualificationPics::getDelFlag, 0);
                qualificationPicsQuery.orderByAsc(PmsProductQualificationPics::getSort);
                List<PmsProductQualificationPics> qualificationPics = pmsProductQualificationPicsService.list(qualificationPicsQuery);
                if (qualificationPics.size() > 0) {
                    isQualification = true;
                    qualificationPicList = qualificationPics.stream().map(PmsProductQualificationPics::getPicUrl).collect(Collectors.toList());
                } else {
                    errMsg.append("货号" + product.getProductSn() + "同步到微信需要认证，请维护认证信息");
                    return;
                }
            }
            PmsSkuStock skuStock = skuMaps.get(product.getId());
            List<PmsProductPics> picsList = picMap.get(product.getId());
            List<String> imgList = new ArrayList<>();
            StringBuilder getImgUrl = new StringBuilder();
            getImgUrl.append(BizUtil.getWxmaUrl());
            getImgUrl.append("/wx/miniapp/shop/img/");
            getImgUrl.append(openAccount.getClientKey());
            getImgUrl.append("/upload");
            picsList.stream().forEach(r -> {
                String imgResult = HttpUtil.getRequest(getImgUrl.toString() + "?imgUrl=" + r.getPicUrl());
                //log.info("imgResult:"+ imgResult);
                JSONObject imgResultObj = JSON.parseObject(imgResult);
                if (oConvertUtils.isNotEmpty(imgResultObj.getJSONObject("result").getString("tempImgUrl"))) {
                    imgList.add(imgResultObj.getJSONObject("result").getString("tempImgUrl"));
                }
            });

            WxMaShopSpuInfo shopSpuInfo = new WxMaShopSpuInfo();
            shopSpuInfo.setOutProductId(product.getId().toString());
            shopSpuInfo.setTitle(product.getName());

            String productPath = "pages/index/index?url={rootUrl}%2Fgoods%2F{productSn}-{partnerId}-{storeId}%3Futm_source%3DweixinMiniProgram%26utm_campaign%3Dmain";
            productPath = productPath.replace("{rootUrl}", BizUtil.getRootUrl())
                    .replace("{productSn}", product.getProductSn())
                    .replace("{partnerId}", "" + sysUser.getPartnerId())
                    .replace("{storeId}", "" + skuStock.getStoreId());
            shopSpuInfo.setPath(productPath);
            //shopSpuInfo.setHeadImg(picsList.stream().map(PmsProductPics::getPicUrl).collect(Collectors.toList()));
            shopSpuInfo.setHeadImg(imgList);
            if (isQualification) {
                List<String> qImgList = new ArrayList<>();
                qualificationPicList.stream().forEach(q -> {
                    String imgResult = HttpUtil.getRequest(getImgUrl.toString() + "?imgUrl=" + q);
                    //log.info("imgResult:"+ imgResult);
                    JSONObject imgResultObj = JSON.parseObject(imgResult);
                    if (oConvertUtils.isNotEmpty(imgResultObj.getJSONObject("result").getString("tempImgUrl"))) {
                        qImgList.add(imgResultObj.getJSONObject("result").getString("tempImgUrl"));
                    }
                });
                shopSpuInfo.setQualificationPics(qImgList);
            }
            shopSpuInfo.setThirdCatId(category.getWxCatId());
            // Todo 待修改正式的 品牌ID
            shopSpuInfo.setBrandId(26512);
            List<WxMaShopSkuInfo> skuInfos = new ArrayList<>();
            WxMaShopSkuInfo shopSkuInfo = new WxMaShopSkuInfo();
            shopSkuInfo.setOutProductId(product.getId().toString());
            shopSkuInfo.setOutSkuId(skuStock.getId().toString());
            if (true) {
                String imgResult = HttpUtil.getRequest(getImgUrl.toString() + "?imgUrl=" + product.getPic());
                //log.info("imgResult:"+ imgResult);
                JSONObject imgResultObj = JSON.parseObject(imgResult);
                if (oConvertUtils.isNotEmpty(imgResultObj.getJSONObject("result").getString("tempImgUrl"))) {
                    shopSkuInfo.setThumbImg(imgResultObj.getJSONObject("result").getString("tempImgUrl"));
                }
            }
            shopSkuInfo.setSalePrice(oConvertUtils.isEmpty(skuStock.getPromotionPrice()) ? conversionCentAmount(skuStock.getPrice()) : conversionCentAmount(skuStock.getPromotionPrice()));
            shopSkuInfo.setMarketPrice(conversionCentAmount(product.getOriginalPrice()));
            shopSkuInfo.setStockNum(skuStock.getStock() - skuStock.getLockStock());
            shopSkuInfo.setBarcode(skuStock.getSkuCode());
            shopSkuInfo.setSkuCode(skuStock.getSkuCode());

            List<WxMaShopSkuAttribute> attributeList = new ArrayList<>();
            WxMaShopSkuAttribute attribute = new WxMaShopSkuAttribute();
            attribute.setAttrKey("型号");
            attribute.setAttrValue(product.getProductSn());
            attributeList.add(attribute);
            shopSkuInfo.setSkuAttributeList(attributeList);
            skuInfos.add(shopSkuInfo);
            shopSpuInfo.setSkus(skuInfos);
            StringBuilder url = new StringBuilder();
            url.append(BizUtil.getWxmaUrl());
            url.append("/wx/miniapp/shop/spu/");
            url.append(openAccount.getClientKey());
            //url.append("wx5003af1ba4f23e32");
            if (isNewFlag)
                url.append("/addSpu");
            else
                url.append("/updateSpu");
            String result = HttpUtil.postJsonRequest(url.toString(), JSON.toJSONString(shopSpuInfo));
            // {"success":false,"message":"调用的类目id不存在 rid: 60f698e3-37a6aafb-28804261","code":1000009,"result":null,"timestamp":1626773731049}
            //{"success":true,"message":"操作成功！","code":200,"result":{"productId":"412689327","outProductId":"300","createTime":"2021-07-21 14:06:50","updateTime":null,"skus":[{"skuId":"352085081","outSkuId":"300"}]},"timestamp":1626847610219}
            log.info("result: {}", result);
            if (oConvertUtils.isNotEmpty(result)) {
                JSONObject resultObj = JSON.parseObject(result);
                if (resultObj.getBoolean("success")) {
                    if (isNewFlag) {
                        LambdaUpdateWrapper<PmsProduct> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(PmsProduct::getId, product.getId());
                        updateWrapper.set(PmsProduct::getWxStatus, 1);
                        pmsProductService.update(updateWrapper);
                    }
                } else {
                    errMsg.append(resultObj.getString("message"));
                }
            }
        });
        if (oConvertUtils.isNotEmpty(errMsg.toString())) return Result.error(errMsg.toString());
        return Result.ok("同步微信商品成功！");
    }

    private int conversionCentAmount(BigDecimal amount) {
        return amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
    }


    /**
     * 微信小程序交易组件获取商品
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品信息-微信小程序交易组件获取交易组件商品信息")
    @ApiOperation(value = "商品信息-微信小程序交易组件获取交易组件商品信息", notes = "商品信息-微信小程序交易组件获取交易组件商品信息")
    @GetMapping(value = "/wxmaGetProduct")
    public Result<?> wxmaGetProduct(@RequestParam(name = "id", required = true) String id) {
        if (oConvertUtils.isEmpty(id)) return Result.error("同步错误，传入参数有问题！");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysOpenAccount openAccount = sysOpenAccountService.getAccountByPartnerAndBizCode(sysUser.getPartnerId(), CommonConstant.OPEN_ACCOUNT_BIZ_CODE_MINIAPP, CommonConstant.OPEN_ACCOUNT_SOURCE_WECHAT);
        if (oConvertUtils.isEmpty(openAccount)) return Result.error("开发平台账户配置表未配账号，请联系管理员！");
        StringBuilder url = new StringBuilder();
        url.append(BizUtil.getWxmaUrl());
        url.append("/wx/miniapp/shop/spu/");
        url.append(openAccount.getClientKey());
        url.append("/getSpu");
        url.append("?id=" + id);
        url.append("&needEditSpu=0");
        String result = HttpUtil.getRequest(url.toString());
        log.info("result: {}", result);
        return Result.ok(result);
    }

    //===========================以下是子表信息操作相关API====================================

    /**
     * 通过主表id查询SKU
     *
     * @param pmsSkuStock
     * @return
     */
    @GetMapping(value = "/listPmsSkuStockByMainId")
    public Result<?> listPmsSkuStockByMainId(PmsSkuStock pmsSkuStock,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        if (pmsSkuStock.getProductId() != null) {
            QueryWrapper<PmsSkuStock> queryWrapper = QueryGenerator.initQueryWrapper(pmsSkuStock, req.getParameterMap());
            //queryWrapper.select("id","product_id","sku_code","price","stock","low_stock","promotion_price");
            //queryWrapper.select(PmsSkuStock.class,i-> !i.getColumn().equals("lock_stock"));
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            List<StmStoreInfo> effectiveStores = storeInfos.stream()
                    .filter(q -> q.getStatus() > 0)
                    .collect(Collectors.toList());
            List<Long> storeIds = effectiveStores.stream().filter(a -> a.getStoreType() == 1).map(StmStoreInfo::getStoreId).collect(Collectors.toList());
            if (storeIds.contains(0l)) {
                storeIds.remove(0l);
            }
            queryWrapper.in("store_id", storeIds);
            Page<PmsSkuStock> page = new Page<PmsSkuStock>(pageNo, pageSize);
            IPage<PmsSkuStock> pageList = pmsSkuStockService.page(page, queryWrapper);
            if (pageList.getTotal() > 0) {
                Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
                pageList.getRecords().forEach(stock -> {
                    if (oConvertUtils.isNotEmpty(stock.getStoreId())) {
                        if (storeInfoMaps.containsKey(stock.getStoreId())) {
                            stock.setStoreId_dictText(storeInfoMaps.get(stock.getStoreId()));
                        } else {
                            if (Objects.equals(0L, stock.getStoreId())) {
                                stock.setStoreId_dictText("线上商城");
                            }
                        }
                    }
                });
            }
            return Result.ok(pageList);
        } else {
            return Result.error("请选择商品");
        }
    }

    /**
     * 通过主表id查询全部SKU
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryPmsSkuStockByMainId")
    public Result<?> queryPmsSkuStockByMainId(@RequestParam(name = "id", required = true) Long id) {
        LambdaQueryWrapper<PmsSkuStock> skuQuery = new LambdaQueryWrapper<>();
        skuQuery.eq(PmsSkuStock::getProductId, id);
        skuQuery.eq(PmsSkuStock::getStoreId, 0L);
        List<PmsSkuStock> skus = pmsSkuStockService.list(skuQuery);
        return Result.ok(skus);
    }


    /**
     * 添加SKU
     *
     * @param pmsSkuStock
     * @return
     */
    @AutoLog(value = "商品信息-新增SKU")
    @ApiOperation(value = "商品信息-新增SKU", notes = "商品信息-新增SKU")
    @PostMapping(value = "/addPmsSkuStock")
    public Result<?> addPmsSkuStock(@RequestBody PmsSkuStock pmsSkuStock) {
        PmsProduct pmsProduct = pmsProductService.getById(pmsSkuStock.getProductId());
        pmsSkuStock.setSkuCode(pmsProduct.getSkuCode());
        LambdaQueryWrapper<PmsSkuStock> query = new LambdaQueryWrapper<>();
        query.eq(PmsSkuStock::getProductId, pmsSkuStock.getProductId());
        List<Long> storeIds = new ArrayList<>();
        if (oConvertUtils.isNotEmpty(pmsSkuStock.getStoreIds())) {
            storeIds.addAll(Arrays.asList(pmsSkuStock.getStoreIds().split(",")).stream().map(s -> Long.valueOf(s.toString())).collect(Collectors.toList()));
        } else {
            storeIds.add(0L);
        }
        query.in(PmsSkuStock::getStoreId, storeIds);
        int count = pmsSkuStockService.count(query);
        if (count == 0) {
//            if (!checkProductPrice(pmsSkuStock)) {
//                return Result.error("添加SKU失败，价格不允许低于管控价！");
//            }
            List<PmsSkuStock> skuStocks = new ArrayList<>();
            storeIds.forEach(l -> {
                PmsSkuStock stock = BeanUtils.instantiateClass(PmsSkuStock.class);
                BeanUtils.copyProperties(pmsSkuStock, stock);
                stock.setStock(pmsSkuStock.getCurrentStock());
                stock.setProductSn(pmsProduct.getProductSn());
                stock.setSale(0);
                stock.setLockStock(0);
                stock.setStoreId(l);
                stock.setStorePrice(pmsSkuStock.getPrice());
                skuStocks.add(stock);
            });
            if (oConvertUtils.isNotEmpty(skuStocks) && skuStocks.size() > 0) {
                pmsSkuStockService.saveBatch(skuStocks);
                updateProductPrice(pmsSkuStock);
            }
            return Result.ok("添加SKU成功！");
        } else {
            return Result.error("该商品已存在对应的SKU，不允许再次新增，如有新的需求，请联系管理员");
        }
    }

    /**
     * 价格校验
     *
     * @param pmsSkuStock
     * @return
     */
    private Boolean checkProductPrice(PmsSkuStock pmsSkuStock) {
        PmsProductPriceRegulate productPriceRegulate = pmsProductPriceRegulateService.getBySkuCode(pmsSkuStock.getSkuCode());
        if (productPriceRegulate == null) return true;    //限价没有维护，则通过校验
        if (productPriceRegulate.getNormalPrice() == null && productPriceRegulate.getMinPrice() == null) return true;
        BigDecimal price = productPriceRegulate.getMinPrice() != null ? productPriceRegulate.getMinPrice() : productPriceRegulate.getNormalPrice();
        if (null != pmsSkuStock.getPrice()) {
            if (pmsSkuStock.getPrice().compareTo(price) == -1) {
                return false;
            }
        }
        if (null != pmsSkuStock.getPromotionPrice()) {
            if (pmsSkuStock.getPromotionPrice().compareTo(price) == -1) {
                return false;
            }
        }
        return true;
    }

    /**
     * 初始化门店库存
     *
     * @param pmsSkuStocks
     */
    private void initStmStock(List<PmsSkuStock> pmsSkuStocks) {
        if (oConvertUtils.isEmpty(pmsSkuStocks) || pmsSkuStocks.size() == 0) return;
        PmsProduct pmsProduct = pmsProductService.getById(pmsSkuStocks.get(0).getProductId());
        List<StmStock> stmStocks = new ArrayList<>();
        pmsSkuStocks.forEach(l -> {
            if (0l != l.getStoreId()) {
                StmStock stock = new StmStock();
                stock.setStoreId(l.getStoreId());
                stock.setProductId(l.getProductId());
                stock.setProductSn(pmsProduct.getProductSn());
                stock.setSkuCode(l.getSkuCode());
                stmStocks.add(stock);
            }
        });
        if (oConvertUtils.isNotEmpty(stmStocks) && stmStocks.size() > 0) {
            stmStockService.saveBatch(stmStocks);
        }
    }

    /**
     * 根据SKU更新商品价格，临时使用，兼容前端
     *
     * @param pmsSkuStock
     */
    private void updateProductPrice(PmsSkuStock pmsSkuStock) {
        PmsProduct pmsProduct = new PmsProduct();
        pmsProduct.setId(pmsSkuStock.getProductId());
        if (null != pmsSkuStock.getPrice())
            pmsProduct.setPrice(pmsSkuStock.getPrice());
        if (null != pmsSkuStock.getPromotionPrice())
            pmsProduct.setPromotionPrice(pmsSkuStock.getPromotionPrice());
        pmsProductService.updateById(pmsProduct);
        /*StmProduct stmProduct = BeanUtils.instantiateClass(StmProduct.class);
        BeanUtils.copyProperties(pmsProduct, stmProduct);
        stmProductService.updateById(stmProduct);*/
    }

    /**
     * 编辑SKU
     *
     * @param pmsSkuStock
     * @return
     */
    @AutoLog(value = "商品信息-编辑SKU")
    @ApiOperation(value = "商品信息-编辑SKU", notes = "商品信息-编辑SKU")
    @PutMapping("/editPmsSkuStock")
    public Result<?> editPmsSkuStock(@RequestBody PmsSkuStock pmsSkuStock) {
//        if (!checkProductPrice(pmsSkuStock)) {
//            return Result.error("编辑SKU失败，价格不允许低于管控价！");
//        }
        PmsSkuStock dbStock = pmsSkuStockService.getById(pmsSkuStock.getId());
        pmsSkuStock.setStock(pmsSkuStock.getCurrentStock() + dbStock.getLockStock());
        pmsSkuStockService.updateById(pmsSkuStock);
        updateProductPrice(pmsSkuStock);
        return Result.ok("编辑SKU成功！");
    }

    /**
     * 批量编辑SKU
     *
     * @param pmsSkuStockModel
     * @return
     */
    @AutoLog(value = "商品信息-批量编辑SKU")
    @ApiOperation(value = "商品信息-批量编辑SKU", notes = "商品信息-批量编辑SKU")
    @PutMapping("/editBatchPmsSkuStock")
    public Result<?> editBatchPmsSkuStock(@RequestBody PmsSkuStockModel pmsSkuStockModel) {
        /*if (!checkProductPrice(pmsSkuStock)) {
            return Result.error("编辑SKU失败，价格不允许低于管控价！");
        }*/
        if (oConvertUtils.isEmpty(pmsSkuStockModel) || oConvertUtils.isEmpty(pmsSkuStockModel.getIds())
                || oConvertUtils.isEmpty(pmsSkuStockModel.getProductId())
                || oConvertUtils.isEmpty(pmsSkuStockModel.getPrice())
                || oConvertUtils.isEmpty(pmsSkuStockModel.getPromotionPrice())) {
            return Result.error("参数错误，请重试！");
        }
        LambdaUpdateWrapper<PmsSkuStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(PmsSkuStock::getId, pmsSkuStockModel.getIds());
        updateWrapper.set(PmsSkuStock::getPrice, pmsSkuStockModel.getPrice());
        updateWrapper.set(PmsSkuStock::getStorePrice, pmsSkuStockModel.getPrice());
        updateWrapper.set(PmsSkuStock::getPromotionPrice, pmsSkuStockModel.getPromotionPrice());
        pmsSkuStockService.update(updateWrapper);
        PmsSkuStock skuStock = new PmsSkuStock();
        skuStock.setProductId(pmsSkuStockModel.getProductId());
        skuStock.setPrice(pmsSkuStockModel.getPrice());
        skuStock.setPromotionPrice(pmsSkuStockModel.getPromotionPrice());
        updateProductPrice(skuStock);
        return Result.ok("批量改价成功！");
    }

    /**
     * 通过id删除SKU
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deletePmsSkuStock")
    public Result<?> deletePmsSkuStock(@RequestParam(name = "id", required = true) Long id) {
        pmsSkuStockService.removeById(id);
        return Result.ok("删除SKU成功！");
    }

    /**
     * 批量删除SKU
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchPmsSkuStock")
    public Result<?> deleteBatchPmsSkuStock(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.pmsSkuStockService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    /**
     * 通过productSn查询skuCode
     *
     * @param productSn
     * @return
     */
    @AutoLog(value = "通过productSn查询skuCode")
    @ApiOperation(value = "通过productSn查询skuCode", notes = "通过productSn查询skuCode")
    @GetMapping(value = "/fromProductSnToSkuCode")
    public Result<?> fromProductSnToSkuCode(@RequestParam(name = "productSn", required = true) String productSn) {
        LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<PmsProduct>();
        query.eq(PmsProduct::getProductSn, productSn);
        PmsProduct product = pmsProductService.getOne(query, false);
        LambdaQueryWrapper<PmsSkuStock> skuQuery = new LambdaQueryWrapper<PmsSkuStock>();
        skuQuery.eq(PmsSkuStock::getProductId, product.getId());
        skuQuery.isNotNull(PmsSkuStock::getSkuCode);
        PmsSkuStock stock = pmsSkuStockService.getOne(skuQuery, false);
        String skuCode = "";
        if (oConvertUtils.isNotEmpty(stock)) {
            skuCode = stock.getSkuCode();
        }
        return Result.ok(skuCode);
    }

    /**
     * 通过productSn查询skuCode
     *
     * @param productSn
     * @return
     */
    @AutoLog(value = "通过productSn查询skuCode")
    @ApiOperation(value = "通过productSn查询商品信息", notes = "通过productSn查询skuCode")
    @GetMapping(value = "/fromProductSnToProduct")
    public Result<?> fromProductSnToProduct(@RequestParam(name = "productSn", required = true) String productSn) {
        LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<PmsProduct>();
        query.eq(PmsProduct::getProductSn, productSn);
        PmsProduct product = pmsProductService.getOne(query, false);
        return Result.ok(product);
    }

    //=================================================================================================

    /**
     * 通过主表id查询商品图片
     *
     * @param pmsProductPics
     * @return
     */
    @GetMapping(value = "/listPmsProductPicsByMainId")
    public Result<?> listPmsProductPicsByMainId(PmsProductPics pmsProductPics,
                                                HttpServletRequest req) {
        if (pmsProductPics.getProductId() != null) {
            LambdaQueryWrapper<PmsProductPics> query = new LambdaQueryWrapper<>();
            query.eq(PmsProductPics::getProductId, Long.valueOf(pmsProductPics.getProductId()));
            query.orderByAsc(PmsProductPics::getSort);
            List<PmsProductPics> pics = pmsProductPicsService.list(query);
            return Result.ok(pics);
        } else {
            return Result.error("");
        }
    }

    /**
     * 添加商品图片
     *
     * @param pmsProductPics
     * @return
     */
    @PostMapping(value = "/addPmsProductPics")
    public Result<?> addPmsProductPics(@RequestBody PmsProductPics pmsProductPics) {
        pmsProductPicsService.save(pmsProductPics);
        return Result.ok("添加商品图片成功！");
    }

    /**
     * 编辑商品图片
     *
     * @param pmsProductPicsModel
     * @return
     */
    @PutMapping("/editPmsProductPics")
    public Result<?> editPmsProductPics(@RequestBody PmsProductPicsModel pmsProductPicsModel) {
        List<PmsProductPics> editDateSource = pmsProductPicsModel.getPicDataSource();
        List<PmsProductPics> delDateSource = pmsProductPicsModel.getDelDateSource();
        List<PmsProductPics> addPic = new ArrayList<>();
        List<Long> removeOldPic = new ArrayList<>();
        for (PmsProductPics del : delDateSource) {
            if (del.getId() != null) {
                removeOldPic.add(del.getId());
            }
        }
        if (removeOldPic.size() > 0)
            pmsProductPicsService.removeByIds(removeOldPic);
        for (PmsProductPics edit : editDateSource) {
            if (edit.getId() != null) {
                pmsProductPicsService.updateById(edit);
            } else {
                addPic.add(edit);
            }
        }
        if (addPic.size() > 0)
            pmsProductPicsService.saveBatch(addPic);
        return Result.ok("编辑商品图片成功！");
    }

    /**
     * 通过id删除商品图片
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deletePmsProductPics")
    public Result<?> deletePmsProductPics(@RequestParam(name = "id", required = true) String id) {
        pmsProductPicsService.removeById(id);
        return Result.ok("删除商品图片成功！");
    }

    /**
     * 批量删除商品图片
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchPmsProductPics")
    public Result<?> deleteBatchPmsProductPics(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.pmsProductPicsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    //=================================================================================================

    /**
     * 通过主表id查询商品认证图片
     *
     * @param pmsProductQualificationPics
     * @return
     */
    @GetMapping(value = "/listPmsProductQualificationPicsByMainId")
    public Result<?> listPmsProductQualificationPicsByMainId(PmsProductQualificationPics pmsProductQualificationPics,
                                                             HttpServletRequest req) {
        if (pmsProductQualificationPics.getProductId() != null) {
            LambdaQueryWrapper<PmsProductQualificationPics> query = new LambdaQueryWrapper<>();
            query.eq(PmsProductQualificationPics::getProductId, Long.valueOf(pmsProductQualificationPics.getProductId()));
            query.orderByAsc(PmsProductQualificationPics::getSort);
            List<PmsProductQualificationPics> pics = pmsProductQualificationPicsService.list(query);
            return Result.ok(pics);
        } else {
            return Result.error("");
        }
    }

    /**
     * 添加商品图片
     *
     * @param pmsProductQualificationPics
     * @return
     */
    @PostMapping(value = "/addPmsProductQualificationPics")
    public Result<?> addPmsProductQualificationPics(@RequestBody PmsProductQualificationPics pmsProductQualificationPics) {
        pmsProductQualificationPicsService.save(pmsProductQualificationPics);
        return Result.ok("添加商品图片成功！");
    }

    /**
     * 编辑商品图片
     *
     * @param pmsProductQualificationPicsModel
     * @return
     */
    @PutMapping("/editPmsProductQualificationPics")
    public Result<?> editPmsProductQualificationPics(@RequestBody PmsProductQualificationPicsModel pmsProductQualificationPicsModel) {
        List<PmsProductQualificationPics> editDateSource = pmsProductQualificationPicsModel.getPicDataSource();
        List<PmsProductQualificationPics> delDateSource = pmsProductQualificationPicsModel.getDelDateSource();
        List<PmsProductQualificationPics> addPic = new ArrayList<>();
        List<Long> removeOldPic = new ArrayList<>();
        for (PmsProductQualificationPics del : delDateSource) {
            if (del.getId() != null) {
                removeOldPic.add(del.getId());
            }
        }
        if (removeOldPic.size() > 0)
            pmsProductQualificationPicsService.removeByIds(removeOldPic);
        for (PmsProductQualificationPics edit : editDateSource) {
            if (edit.getId() != null) {
                pmsProductQualificationPicsService.updateById(edit);
            } else {
                addPic.add(edit);
            }
        }
        if (addPic.size() > 0)
            pmsProductQualificationPicsService.saveBatch(addPic);
        return Result.ok("编辑商品图片成功！");
    }

    /**
     * 通过id删除商品图片
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deletePmsProductQualificationPics")
    public Result<?> deletePmsProductQualificationPics(@RequestParam(name = "id", required = true) String id) {
        pmsProductQualificationPicsService.removeById(id);
        return Result.ok("删除商品图片成功！");
    }

    /**
     * 批量删除商品图片
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchPmsProductQualificationPics")
    public Result<?> deleteBatchPmsProductQualificationPics(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.pmsProductQualificationPicsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    /**
     * 导出excel
     *
     * @param request
     * @param pmsProduct
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PmsProduct pmsProduct) {

        QueryWrapper<PmsProduct> queryWrapper = QueryGenerator.initQueryWrapper(pmsProduct, request.getParameterMap());
        List<PmsProduct> productList = pmsProductService.list(queryWrapper);

        List<PmsProductCategory> pmsProductCategories = pmsProductCategoryService.list();
        Map<Long, PmsProductCategory> pmsProductCategoryMap = new HashMap<>();
        pmsProductCategories.forEach(a -> pmsProductCategoryMap.put(a.getId(), a));

        productList.forEach(a -> {
            if (a.getProductCategoryId() != null) {
                if (pmsProductCategoryMap.get(a.getProductCategoryId()).getLevel() == 1) {
                    a.setProductCategoryNameLevel1(a.getProductCategoryName());
                } else {
                    Long parentId = pmsProductCategoryMap.get(a.getProductCategoryId()).getParentId();
                    a.setProductCategoryNameLevel1(pmsProductCategoryMap.get(parentId).getName());
                }
            }
        });

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<PmsProductExportVO> exportVOS = new ArrayList<>();
        PmsProductExportVO exportVO;
        for (PmsProduct product : productList) {
            exportVO = new PmsProductExportVO();
            BeanUtils.copyProperties(product, exportVO);
            exportVOS.add(exportVO);
        }

        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "商品信息");
        mv.addObject(NormalExcelConstants.CLASS, PmsProductExportVO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品信息", "导出人:" + sysUser.getRealname(), "商品信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportVOS);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PmsProduct.class);
    }


    /**
     * 编辑
     *
     * @param pmsProductModel
     * @return
     */
    @AutoLog(value = "商品信息-编辑价格")
    @ApiOperation(value = "商品信息-编辑价格", notes = "商品信息-编辑价格")
    @PostMapping(value = "/editPrice")
    public Result<?> editPrice(@RequestBody PmsProductModel pmsProductModel) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        PmsProduct pmsProduct = pmsProductService.getById(pmsProductModel.getId());
        pmsProduct.setPrice(pmsProductModel.getPrice());
        pmsProduct.setUpdateTime(new Date());
        pmsProduct.setUpdateBy(sysUser.getRealname());
        pmsProductService.updateById(pmsProduct);

        return Result.ok("编辑成功!");
    }
}
